package sendmail;

import java.io.IOException;
import java.text.DateFormat;
import java.util.Date;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.Set;
import java.util.logging.Logger;

import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.FetchOptions;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.datastore.Query;
import com.google.appengine.api.datastore.Text;

@SuppressWarnings("serial")
public class SendMailServlet extends HttpServlet {
	private static final Logger log = Logger.getLogger(SendMailServlet.class
			.getName());

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		String lang = Constants.LANG_ENGLISH;
		if (Constants.LANG_KOREAN.equalsIgnoreCase(req
				.getParameter(Constants.LANG))) {
			lang = Constants.LANG_KOREAN;
		}
		String email = req.getParameter(Constants.EMAIL);
		if (email == null) {
			redirect(req, resp, lang);
			return;
		}
		email = email.trim();
		if (!isValidEmailAddress(email)) {
			redirect(req, resp, lang);
			return;
		}

		Properties properties = new Properties();
		Session session = Session.getDefaultInstance(properties, null);

		try {
			DatastoreService dataService = DatastoreServiceFactory
					.getDatastoreService();
			// save email address to datastore

			Key langKey = KeyFactory.createKey(Constants.LANG, lang);
			Entity downloadRequest = new Entity(Constants.EMAIL, langKey);
			Date date = new Date();
			downloadRequest.setProperty(Constants.DATE, date);
			downloadRequest.setProperty(Constants.EMAIL, email);
			dataService.put(downloadRequest);

			// load email

			Entity entity = dataService.get(KeyFactory.createKey(
					Constants.KIND_MAIL_CONTENT, lang));
			String subject = (String) entity.getProperty(Constants.SUBJECT);
			Object property = entity.getProperty(Constants.BODY);
			String body;
			if (property instanceof Text)
				body = ((Text) property).getValue();
			else
				body = (String) property;
			// send email
			Multipart mp = new MimeMultipart();
			MimeBodyPart html = new MimeBodyPart();
			html.setContent(body, "text/html");
			mp.addBodyPart(html);
			Message msg = new MimeMessage(session);
			msg.setFrom(new InternetAddress("tau.uistudio@gmail.com",
					"TAU UI Studio"));
			msg.addRecipient(Message.RecipientType.BCC, new InternetAddress(
					email));
			msg.setSubject(subject);
			msg.setContent(mp);
			Transport.send(msg);
		} catch (Throwable e) {
			throw new RuntimeException(e);
		}
		resp.sendRedirect("/response.jsp?email=" + email);
	}

	private void redirect(HttpServletRequest req, HttpServletResponse resp, String lang)
			throws IOException {
		String url = "/index.jsp?status=error&lang=" + lang;
		resp.sendRedirect(url);
	}

	public static boolean isValidEmailAddress(String email) {
		return email
				.matches("^[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$");
	}
}
